package com.goods.shop.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ExecutorServieCalculator implements Calculator {
    private int parallis;
    private ExecutorService pool;
    public ExecutorServieCalculator(){
        parallis=Runtime.getRuntime().availableProcessors();
        pool= Executors.newFixedThreadPool(parallis);
    }
    private static class SumTask implements Callable<Long>{
        private int[] numbers;
        private int from;
        private int to;
        public SumTask(int[] numbers,int from,int to){
            this.numbers=numbers;
            this.from=from;
            this.to=to;
        }
        @Override
        public Long call() throws Exception {
            long total=0;
            for(int i=from;i<to;i++){
                total+=numbers[i];
            }
            return total;
        }
    }
    @Override
    public long sum(int[] datas) {
        List<Future<Long>> results=new ArrayList<>();
        int part=datas.length/parallis;
        for(int i=0;i<parallis;i++){
            int from=i*part;
            int to=(i==parallis-1)?datas.length:(i+1)*part;
            results.add(pool.submit(new SumTask(datas,from,to)));
        }
        long total=0;
        for(Future<Long> f:results){
            try {
                total+=f.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        return total;
    }
}
